import axios from 'axios'
import { getTokenKey } from '../utils/contants'

//基础路径的定义  http://localhost:5173/api/user/login
axios.defaults.baseURL = 'http://localhost:8960/'

//请求超时
const request = axios.create({
    timeout: 5000 //5秒后端没有给回响应，此时就会有异常
})

//请求
request.interceptors.request.use(config => {
    //在每次前端向后台发送请求的时候，将token放到请求头  一块送到后端
    const token = localStorage.getItem(getTokenKey()) || sessionStorage.getItem(getTokenKey()) || null
    if(token){
        //把token放入请求头
        config.headers['Authorization'] = token
    }

    //token续期   每次请求的时候，都需要把Redis或者前端的token的有效时间延长
    const t = localStorage.getItem(getTokenKey());
    if(t){
        config.headers['rememberMe'] = true
    }else{
        config.headers['rememberMe'] = false
    }

    return config
},error => {
    return Promise.reject(error)
})

//响应拦截
request.interceptors.response.use(config => {
    return config
},error => {
    return Promise.reject(error)
})

export default request